<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 服务订单接口
 * Class Service
 * @package app\api\controller
 */
class ServiceOrder extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function getServiceOrderList()
    {
        //当前是否为关联查询
        if ($this->request->isPost()) {
            $status = $this->request->post('status');
            $pageIndex = $this->request->post('pageIndex', 1);
            $pageSize = $this->request->post('pageSize', 10);
            // 1是管理员、2普通用户
            $origin = $this->request->post('origin', 2);
            $user = $this->auth->getUser();
            $where = [];
            if ($origin == 2) {
                $where['user_id'] = $user['id'];
            } elseif ($origin == 1) {
                // 是否是超级管理员
                if ($user['group_id'] == 2) {
                    $this->error(__('You have no permission'));
                }
            } else {
                $this->error(__('Parameter error'));
            }
            if ($status >= 0) {
                $where['jso.status'] = $status;
            }
            $list = model('\app\admin\model\jy\ServiceOrder')->alias('jso')
                ->field('jso.*, DATE_FORMAT(jso.create_time, "%Y-%m-%d %H:%i") createTime, js.service_name, 
                js.sub_name, js.cover_image, js.price')
                ->join('jy_service js', 'jso.service_id = js.id', 'LEFT')
                ->where(['jso.is_del' => 0])
                ->where($where)
                ->order('jso.create_time desc')
                ->paginate($pageSize, false, ['page' => $pageIndex]);
            foreach ($list->items() as &$item) {
                if ($item['cover_image']) {
                    $item['cover_image'] = cdnurl($item['cover_image']);
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            $this->success('', $result);
        }
    }

    public function submitServiceOrder()
    {
        if ($this->request->isPost()) {
            $serviceId = $this->request->post('serviceId');
            $username = $this->request->post('username');
            $phone = $this->request->post('phone');
            $city = $this->request->post('city');
            $address = $this->request->post('address');
            $remark = $this->request->post('remark');
            if (!$serviceId) {
                $this->error(__('Parameter %s can not be empty', 'serviceId'));
            }
            if (!$username) {
                $this->error(__('Parameter %s can not be empty', 'username'));
            }
            if (!$phone) {
                $this->error(__('Parameter %s can not be empty', 'phone'));
            }
            if (!$city) {
                $this->error(__('Parameter %s can not be empty', 'city'));
            }
            if (!$address) {
                $this->error(__('Parameter %s can not be empty', 'address'));
            }
            $service = model('\app\admin\model\jy\Service')
                ->where(['id' => $serviceId, 'is_del' => 0])
                ->whereIn('status', [1, 2])
                ->find();
            if (!$service) {
                $this->error(__('服务不可用'), null, 999);
            }
            $userId = $this->auth->id;
            // 订单
            $order['service_id'] = $serviceId;
            $order['user_id'] = $userId;
            $order['order_no'] = self::genOrderCode();
            $order['username'] = $username;
            $order['phone'] = $phone;
            $order['city'] = $city;
            $order['address'] = $address;
            $order['remark'] = $remark;
            $order['status'] = 0;
            $order['create_user'] = $userId;
            $orderId = model('\app\admin\model\jy\ServiceOrder')->insertGetId($order);
            $this->success('', $orderId);
        }
    }

    // 202107141450543572443
    private function genOrderCode()
    {
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        return $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    }

    public function getServiceOrderById($orderId = NULL)
    {
        if (!$orderId) {
            $this->error(__('Parameter %s can not be empty', 'orderId'));
        }
        $userId = $this->auth->id;
        $order = model('\app\admin\model\jy\ServiceOrder')->alias('jso')
            ->field('jso.*, DATE_FORMAT(jso.create_time, "%Y-%m-%d %H:%i") createTime, js.service_name, 
                js.sub_name, js.cover_image, js.price')
            ->join('jy_service js', 'jso.service_id = js.id', 'LEFT')
            ->where(['jso.is_del' => 0, 'jso.id' => $orderId])
            ->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }
        if ($order['cover_image']) {
            $order['cover_image'] = cdnurl($order['cover_image']);
        }
        $this->success('', $order);
    }

    public function modifyOrderStatus()
    {

        if ($this->request->isPost()) {
            $orderId = $this->request->post('orderId');
            $status = $this->request->post('status');
            if (!$status) {
                $this->error(__('Parameter %s can not be empty', 'status'));
            }
            if (!$orderId) {
                $this->error(__('Parameter %s can not be empty', 'orderId'));
            }
            $user = $this->auth->getUser();
            // 是否是超级管理员
            if ($user['group_id'] == 2) {
                $this->error(__('You have no permission'));
            }
            // 状态：0待确认、1已确认、2已完成、3已取消
            $order = model('\app\admin\model\jy\ServiceOrder')->alias('jso')
                ->field('jso.*, DATE_FORMAT(jso.create_time, "%Y-%m-%d %H:%i") createTime, js.service_name, 
                js.sub_name, js.cover_image, js.price')
                ->join('jy_service js', 'jso.service_id = js.id', 'LEFT')
                ->where(['jso.is_del' => 0, 'jso.id' => $orderId])
                ->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            if ($order['status'] == $status) {
                $this->error(__('Parameter error'));
            }
            if ($order['status'] == 0) {
                // 1已确认、3已取消 - 可以
                if ($status == 2) {
                    $this->error(__('订单还未确认无法完成'));
                }
            } elseif ($order['status'] == 1) {
                // 2已完成、3已取消 - 可以
                if ($status == 0) {
                    $this->error(__('订单已确认无法变更为待确认'));
                }
            } elseif ($order['status'] == 2) {
                $this->error(__('订单已完成，操作失败'));
            } elseif ($order['status'] == 3) {
                $this->error(__('订单已取消，操作失败'));
            }
            $time = date("Y-m-d H:i:s", time());
            $data['id'] = $orderId;
            $data['status'] = $status;
            $data['update_user'] = $user['id'];
            $data['update_time'] = $time;
            model('\app\admin\model\jy\ServiceOrder')->isUpdate(true)->save($data);
            if ($order['cover_image']) {
                $order['cover_image'] = cdnurl($order['cover_image']);
            }
            $order['status'] = $status;
            $order['update_user'] = $user['id'];
            $order['update_time'] = $time;
            $this->success('', $order);
        }
    }

    public function modifyOrderInfo()
    {
        if ($this->request->isPost()) {
            $orderId = $this->request->post('orderId');
            $username = $this->request->post('username');
            $phone = $this->request->post('phone');
            $city = $this->request->post('city');
            $address = $this->request->post('address');
            $remark = $this->request->post('remark');
            if (!$orderId) {
                $this->error(__('Parameter %s can not be empty', 'orderId'));
            }
            if (!$username) {
                $this->error(__('Parameter %s can not be empty', 'username'));
            }
            if (!$phone) {
                $this->error(__('Parameter %s can not be empty', 'phone'));
            }
            if (!$city) {
                $this->error(__('Parameter %s can not be empty', 'city'));
            }
            if (!$address) {
                $this->error(__('Parameter %s can not be empty', 'address'));
            }
            $user = $this->auth->getUser();
            // 是否是超级管理员
            if ($user['group_id'] == 2) {
                $this->error(__('You have no permission'));
            }
            // 状态：0待确认、1已确认、2已完成、3已取消
            $order = model('\app\admin\model\jy\ServiceOrder')
                ->where(['is_del' => 0, 'id' => $orderId])
                ->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            try {
                // 订单
                $order['username'] = $username;
                $order['phone'] = $phone;
                $order['city'] = $city;
                $order['address'] = $address;
                $order['remark'] = $remark;
                $order['update_user'] = $user['id'];
                $order['update_time'] = date("Y-m-d H:i:s", time());
                $order->save();
                $this->success('', $order);
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('');
        }
    }
}